#include <iostream>
#include <string>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "Terminal.hpp" 

static void Usage(const std::string& proc)
{
    std::cout << "Usage\n" << proc << " serverip serverport\n" << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void* recv_message(void* args)
{
    OpenTerminal();
    ThreadData *td = static_cast<ThreadData*>(args);
    char buffer[256];
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(td->sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl;
        }
    }
}

void *send_message(void* args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    std::string message;
    socklen_t len = sizeof(td->server);

    std::string welcome = td->serverip;
    welcome += " comming ....";
    sendto(td->sockfd, welcome.c_str(), welcome.size(), 0, (struct sockaddr*)&(td->server), len);

    while(true)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(td->server), len);
    }
}

int main(int argc, char** argv)
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 3;
    }
    // struct sockaddr_in server;
    struct ThreadData td;
    // socklen_t len = sizeof(td.server);
    bzero(&(td.server), sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(std::stoi(argv[2]));
    td.server.sin_addr.s_addr = inet_addr(argv[1]);

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd < 0)
    {
        std::cout << "create sockfd failed" << std::endl;
        return 1;
    }
    td.serverip = argv[1];

    pthread_t recv, sender;
    pthread_create(&recv, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);

    pthread_join(recv, nullptr);
    pthread_join(sender, nullptr);
    close(td.sockfd);
    return 0;
}